package com.nick.controller;

import com.nick.controller.user.user;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by 下 on 2017/6/12.
 */
@Controller
@RequestMapping({"/user"})
public class MainController {
    private Map<String,user> users=new HashMap<String,user>();

    public MainController() {
        users.put("001",new user("001","123456","king","123"));
        users.put("002",new user("002","123456","second","123"));
        users.put("003",new user("003","123456","third","123"));
        users.put("004", new user("004", "123456", "fourth", "123"));
    }

    @RequestMapping({"/hello"})
    public String hello(){
        return "index";
    }

//    查看学生列表
    @RequestMapping(value = "/users",method = RequestMethod.GET)
    public String usersList(Model model){
        model.addAttribute("user",users);
        return "list";
    }
//     添加学生
/*    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public String add(Model model){
        model.addAttribute(new user());
        return "add";
    }
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public String add(user user){
        users.put(user.getUsername(),user);
        System.out.println(user);
        return "redirect:/user/users";
    }*/

    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public String add(Model model){
        model.addAttribute(new user());
        return "add";
    }
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public String add(@ModelAttribute("user") user user,BindingResult br){
        if (br.hasErrors()){
            return "add";
        }
        users.put(user.getUsername(), user);
        System.out.println(user);
        return "redirect:/user/users";
    }
}
